<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
	  <uni-forms-item name="type" label="类型">
		 <uni-data-checkbox v-model="formData.type" :localdata="formOptions.type_localdata"></uni-data-checkbox>
	  </uni-forms-item>
      <uni-forms-item name="chapter_id" label="章节" required>
        <uni-data-picker v-model="formData.chapter_id" collection="mydb-course-chapter" field="title as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="sentence" label="句子" required>
        <uni-easyinput placeholder="句子" v-model="formData.sentence" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="explain" label="句子释义">
        <uni-easyinput placeholder="句子中文释义" v-model="formData.explain" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="word" label="填空单词" required>
        <uni-easyinput placeholder="填空单词(用户填写的单词)" v-model="formData.word" trim="both"></uni-easyinput>
      </uni-forms-item>
		<uni-forms-item v-for="(item,index) in dynamicLists" :key="item.id" :label="item.label+' '+(index+1)" required
			:rules="item.rules" :name="'words[' + item.id + ']'">
			<view class="form-item">
				<uni-easyinput v-model="dynamicFormData.words[item.id]" placeholder="请输入选项单词" />
				<uni-easyinput v-model="dynamicFormData.names[item.id]" placeholder="请输入选单词释义" />
				<button class="button" size="mini" type="default" @click="del(item.id)">删除</button>
			</view>
		</uni-forms-item>
		<button type="warn" size="mini" @click="add">新增选项</button>
      <uni-forms-item name="imgfile" label="图片示例">
        <uni-file-picker file-mediatype="image" return-type="object" v-model="formData.imgfile"></uni-file-picker>
      </uni-forms-item>
	  <uni-forms-item name="description" label="解析">
	    <uni-easyinput placeholder="解析内容" v-model="formData.description" trim="both"></uni-easyinput>
	  </uni-forms-item>
      <uni-forms-item name="sort" label="排序">
        <uni-easyinput placeholder="数字越小，排序越前" type="number" v-model="formData.sort"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="生效状态">
        <switch @change="binddata('status', $event.detail.value)" :checked="formData.status"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-words-sentence.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-words-sentence';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
		"type": 0,
        "chapter_id": "",
        "sentence": "",
        "word": "",
        "explain": "",
        "options": [],
        "imgfile": null,
        "videofile": null,
        "audiofile": null,
        "sort": null,
        "status": true,
        "description": ""
      }
      return {
        formData,
         formOptions: {
		  "type_localdata": [
			{
			  "text": "学习",
			  "value": 0
			},
			{
			  "text": "练习",
			  "value": 1
			}
		  ]
		},
		dynamicFormData: {
			names: {},
			words:{}
		},
		dynamicLists: [],
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      add() {
      	this.dynamicLists.push({
      		label: '单词选项',
      		// rules: [{
      		// 	'required': true,
      		// 	errorMessage: '内容必填'
      		// }],
      		id: Date.now()
      	})
      },
      del(id) {
      	let index = this.dynamicLists.findIndex(v => v.id === id)
      	this.dynamicLists.splice(index, 1)
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
		let options=[]
		this.dynamicLists.forEach((item)=>{
			options.push({
				name:this.dynamicFormData.names[item.id],
				word:this.dynamicFormData.words[item.id],
			})
		})
        this.$refs.form.validate().then((res) => {
			res.options=options
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
